package com.youthburin.base.spring;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import com.youthburin.base.domain.UserInfo;
import com.youthburin.base.util.DwzResponse;
import com.youthburin.base.util.DwzResponseUtils;
import com.youthburin.utils.JsonUtils;

public class CustomHandlerExceptionResolver extends SimpleMappingExceptionResolver {
	private static final Logger logger = LoggerFactory.getLogger(CustomHandlerExceptionResolver.class);

	@Override
	public ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception exception) {
		if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))
				|| request.getParameter("ajax") != null) {
			try {
				DwzResponse dwzResponse = null;
				if (UnauthorizedException.class.isAssignableFrom(exception.getClass())) {
					UserInfo user = (UserInfo) SecurityUtils.getSubject().getPrincipal();
					logger.warn(user.getCode() + "[" + user.getName() + "]ip:" + request.getRemoteHost()
							+ "，用户权限不足，不允许执行当前操作![" + exception.getLocalizedMessage());
					dwzResponse = DwzResponseUtils.createFailResponse(getMessage("error.common.lackpermission",
							request.getSession()));
				} else {
					dwzResponse = DwzResponseUtils.createFailResponse(exception.getMessage());
				}
				JsonUtils.writeObject(response.getOutputStream(), dwzResponse);
				response.getOutputStream().close();
			} catch (IOException ex) {
				throw new RuntimeException(ex);
			}
		} else {
			return super.doResolveException(request, response, handler, exception);
		}
		return null;
	}

	private String getMessage(String code, HttpSession session) {
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());
		return context.getMessage(code, null, code,
				(Locale) session.getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME));
	}
}
